﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Inovout.Cloud.DataWarehouse.Web.Utility
{
    public class HttpUtils
    {
        public static bool PutDataToKafka(JObject obj)
        {
            bool isSuccess = false;

            string json = obj.ToString();
            string sendMessageToKafkaUrl = ConfigurationUtility.GetAppSetting("sendRowsToKafka");
            
            if (sendMessageToKafkaUrl != null && !string.Empty.Equals(sendMessageToKafkaUrl))
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(sendMessageToKafkaUrl);
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method = "POST";
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string result = streamReader.ReadToEnd();
                    if (result != null && !string.Empty.Equals(result) && result.Contains("success"))
                    {
                        isSuccess = true;
                    }
                }
            }

            return isSuccess;
        }
    }
}